// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// m [author] rhyme_lph
// y [email]  rhymelph@gmail.com
// B [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_button.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_white_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/dash_board/contacts_tag_item.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/contact/delete_business_contact_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tuple/tuple.dart';

import 'business_contacts_page.dart';

@RouterMeta(paramName: "deleteBusinessContactPage")
class DeleteBusinessContactPage extends StatefulWidget {
  @override
  _DeleteBusinessContactPageState createState() =>
      _DeleteBusinessContactPageState();
}

class _DeleteBusinessContactPageState extends State<DeleteBusinessContactPage>
    with
        PagePresenter<DeleteBusinessContactPage,
            DeleteBusinessContactProvider> {
  @override
  PreferredSizeWidget get appBar =>
      getDefaultAppBar(title: S.current.delete_business_contact);

  @override
  Widget get buildEmptyWidget => ColoredBox(
        color: Colors.white,
        child: Stack(
          children: [
            Column(
              children: [
                AppSpaces.h20,
                SearchInputField(
                  controller: provider.searchController,
                  focusNode: provider.searchFocusNode,
                ),
                AppSpaces.h20,
                Expanded(
                  child: super.buildEmptyWidget,
                ),
              ],
            ),
            _buildBottomButton(),
          ],
        ),
      );

  Widget _buildBottomButton() => Positioned(
      left: 0.0,
      right: 0.0,
      bottom: getDp(32) + MediaQuery.of(context).padding.bottom,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          NormalFloatTextWhiteButton(
            title: S.current.cancel,
            onTap: provider.onCancel,
          ),
          SizedBox(
            width: getDp(15),
          ),
          NormalFloatTextButton(
            title: S.current.delete,
            onTap: provider.onDeleteDone,
          ),
        ],
      ));

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: Stack(
          children: [
            Column(
              children: [
                AppSpaces.h20,
                SearchInputField(
                  controller: provider.searchController,
                  focusNode: provider.searchFocusNode,
                ),
                AppSpaces.h20,
                Expanded(
                  child: listBuilder<Map<String, List<BusinessContactEntity>>>(
                    selector: (_, __) => Map.from(__.groupMap),
                    builder: (BuildContext context,
                            Map<String, List<BusinessContactEntity>> value,
                            Widget child) =>
                        value.isEmpty
                            ? super.buildEmptyWidget
                            : SmartRefresher(
                                controller: provider.refreshController,
                                onRefresh: provider.onRefresh,
                                onLoading: provider.onLoadMore,
                                enablePullUp: false,
                                child: CustomScrollView(
                                  slivers: buildSearchWidget(),
                                ),
                              ),
                  ),
                ),
              ],
            ),
            _buildBottomButton(),
          ],
        ),
      );

  List<Widget> buildSearchWidget() {
    return provider.groupMap.entries
        .toList()
        .map((e) => buildSliver(e.key, e.value))
        .toList();
  }

  Widget buildSliver(String title, List<BusinessContactEntity> data) =>
      SliverStickyHeader(
        header: buildSliverHeader(title: title),
        sliver: SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, i) => buildSliverItem(data, i),
            childCount: data.length,
          ),
        ),
      );

  Widget buildSliverItem(List<BusinessContactEntity> data, int i) {
    BusinessContactEntity lastItemInList =
        provider.groupMap.entries.toList().map((e) => e.value).last.last;

    return listBuilder<Tuple2<BusinessContactEntity, bool>>(
        selector: (_, __) => Tuple2(
              data[i],
              __.deleteContact == data[i],
            ),
        builder: (BuildContext context,
                Tuple2<BusinessContactEntity, bool> value, Widget child) =>
            Column(
              children: [
                ContactsTagItem(
                  onTap: () => provider.onSelectBusinessContact(data[i]),
                  title: data[i].name,
                  isSelect: value.item2,
                  isSelectMode: true,
                  isCheckStar: value.item1.isFavorite == 1,
                  hasCreditBalance: (value.item1.totalUnpaidCredit +
                          value.item1.totalUnpaidDebit) >
                      0,
                  onClickStar: () {},
                  isOverdue: value.item1.isOverdue == 1,
                  tags: [
                    if (value.item1.isSupplier == 1) 'S',
                    if (value.item1.isClient == 1) 'C'
                  ],
                  isLastItem: data.length == i + 1,
                ),
                if (lastItemInList == value.item1) AppSpaces.h85(context)
              ],
            ));
  }

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return ListHeaderItem(
      title: _title,
    );
  }
}
